import axios from "axios";
import fs from 'fs'
import path from "path";
import AdmZip from '@zwg/adm-zip'

// 确保目标目录存在
function ensureDirectoryExistence(dirPath) {
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
    }
}

// 检查是否已有文件
function checkFileExistsSync(filePath) {
    try {
        return fs.existsSync(filePath); // 或 fs.statSync(filePath).isFile()
    } catch (err) {
        return false;
    }
}

const install = async (url: any,installPath: any)=>{


    const lanZouYun = url
    const jieXiWangZhi = 'https://www.hhlqilongzhu.cn/api/lanzouyun_jx.php'
    try{
        console.log(Date.now());
        console.log(url);
        
        const jieXiResponse = await axios({
            method: 'GET',
            url: jieXiWangZhi,
            params:{
                url: lanZouYun,
                t: Date.now()
            },
            responseType: 'json'
        })
        console.log("解析结果：");
        console.log(jieXiResponse.data);
        if(jieXiResponse.data.code === 200){
            const downUrl = jieXiResponse.data.downUrl
            const fileName = jieXiResponse.data.name
            const outputDir = installPath; // 指定解压目录

            if(!checkFileExistsSync(path.join(outputDir,fileName))){
                try {
                    // 1. 下载压缩包
                    console.log('正在下载...');
                    const response = await axios({
                        method: 'GET',
                        url: downUrl,
                        maxRedirects: 5, 
                        responseType: 'arraybuffer', 
                        timeout: 10000,
                        // 添加下载进度
                        onDownloadProgress: (progressEvent : any) => {
                            const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                            console.log(`下载进度: ${percent}%`);
                        },
                    });
    
                    // 2. 确保输出目录存在
                    ensureDirectoryExistence(outputDir);
    
                    fs.writeFileSync(path.join(outputDir,fileName),Buffer.from(response.data))
    
                } catch (error: any) {
                    console.error('操作失败：', error.message);
                    return '下载失败'
                }
            }
            else{
                console.log("压缩包已存在...");
                
            }
            console.log("开始解压...");
    
            try{
                return await uzip(path.join(outputDir,fileName))
            }catch(error: any){
                console.log("解压失败"+error.message);
                return '解压失败'
            }
            
        }
        return '解析失败'
        
    }catch{
        return '未知错误'
    }
}

async function uzip(filePath: any){
    const outputDir = path.dirname(filePath)
    const zip = new AdmZip(filePath)
    // 2. 获取 ZIP 内的所有条目（文件/目录）
    const entries = zip.getEntries();
    const fileList = entries.map(entry => {
    return {
        name: entry.entryName,          // 文件在 ZIP 中的路径（如 "folder/file.txt"）
        isDirectory: entry.isDirectory, // 是否是目录
        size: entry.header.size,        // 原始大小（压缩前）
        compressedSize: entry.header.compressedSize, // 压缩后大小
    };
    });
    zip.extractAllTo(outputDir,true)
    // 4. 生成解压后的完整路径（可选）
    const extractedFiles = fileList.map(file => ({
        ...file,
        fullPath: path.join(outputDir, file.name), // 解压后的绝对路径
    }));
    console.log('解压完成');

    console.log('解压后的文件列表:', extractedFiles);

    //await deleteExtractedFiles(extractedFiles)

    return extractedFiles
    
}

/*import { promisify } from 'util';

const stat = promisify(fs.stat); // ✅ 转换为 Promise 风格

async function deleteExtractedFiles(extractedFiles) {
  for (const file of extractedFiles) {
    try {
      const stats = await stat(file.fullPath); // ✅ 正确
      if (stats.isDirectory()) {
        await fs.promises.rm(file.fullPath, { recursive: true, force: true });
      } else {
        await fs.promises.unlink(file.fullPath);
      }
      console.log(`已删除: ${file.fullPath}`);
    } catch (err: any) {
      console.error(`删除失败 ${file.fullPath}:`, err.message);
    }
  }
} */

export default install
